# get_readings.py
# http://pyserial.sourceforge.net/shortintro.html
from __future__ import with_statement
import serial, time, sys, os, logging
import simplejson as json
import common, mac

GENERATE_TEST_DATA = True
watts = [0.0]*24
kwh = [0.0]*24
count = 0

def to_volts(count):
    return 0 if count == 0 else 0.0298 * count + 9.7904
 
def get_port():
    if sys.platform == 'win32':
        return 'COM4'
    else:
        for line in os.popen('ls /dev/ttyUSB*'):
            return line[0:-1]

def initialize_port():
    try:
        serial_port = serial.Serial(port, 9600)
    except:
        logging.debug('serial.Serial(port, 9600) failure: '+str(sys.exc_info()))
        #print "Can't open port: ", sys.exc_info()[0]
        raise
    try:
        ready = serial_port.readline()
    except:
        #print "Can't read from port: ", sys.exc_info()[0]
        logging.debug('serial.Serial(port, 9600) failure: '+str(sys.exc_info()))
        raise
    #print ready
    if GENERATE_TEST_DATA: serial_port.write('t') # Set the Arduino to send random data
    logging.debug(ready)
    return serial_port

def get_readings(serial):
    ok = True
    readings = {}
    try:
        serial.write("G")      # write a string
    except:
        time.sleep(1)
        port = get_port()
        serial = serial.Serial(port, 9600)
        ok = False
    try:
        readings = serial.readline().strip().split(' ') 
        # the readings are separated by spaces
        print readings
        # readings = '12.5 .61 2 3 4  6 7 8 9.9 10.1'.strip().split(' ') 
        # the readings are separated by spaces
    except:
        logging.debug('serial.write("G") failure: '+str(sys.exc_info()))
        ok = False
        readingsX = ["0", "0", "0", "0", "0", "0" ,"0", "0",
                    "0", "0", "0", "0", "0", "0" ,"0", "0",
                    "0", "0", "0", "0", "0", "0" ,"0", "0",
                    "0", "0", "0", "0", "0", "0" ,"0", "0"]
    return { 'ok':ok, 'readings': readings }
    
# port = '/dev/ttyUSB0'
# port = 'COM4'
port = get_port()
mac_addr = mac.getMacAddress()

common.setup_logging()
readings_file = 'readings.json' if sys.platform == 'win32' else '/var/www/readings.json'
initial = True
run = True

serial = initialize_port()

while run:
    # volts = int(readings[5],16) * VOLT_FACTOR
    result = get_readings(serial)
    if result['ok']:
        readings = result['readings']
        volts = to_volts(int(readings[5],16))
        amps1 = common.to_amps(9,readings[14])
        amps2 = common.to_amps(10,readings[15])
        reading1 = amps1/1000.0
        watts1 = amps1 * volts
        watts2 = amps2 * volts
        now = time.time()
        for i in range(24):
            watts[i] = volts * common.to_amps(i+1, readings[i+8])
        if not initial:
            interval_seconds = now - prev_readings['time']
            prev_watts = prev_readings['watts']
            for i in range(24):
                avg_watts = (prev_watts[i] + watts[i])/2
                joules = avg_watts*interval_seconds
                kwh[i] += joules/3.6E6
        prev_readings = {'raw': readings, 
                       'datetime': time.ctime(now),
                       'time': now,
                       'volts': volts,
                       'watts1': watts1,
                       'watts2': watts2,
                       'watts': watts,
                       'kwh': kwh,
                       'initial': initial,
                       'mA': reading1,
                       'mac': mac_addr}
        print '***************'
        print json.dumps(prev_readings)
        with open(readings_file, 'w') as f:
            #json.dump([time.ctime(),reading,volts], f)
            json.dump(prev_readings, f)
        initial = False
    try:
        time.sleep(1)
    except:
        logging.debug('sleep interrupted'+str(sys.exc_info()))
        raise
    count += 1
    if count > 5: run = False
    #run = False
